package com.gc.ykqx.ui.fragment;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.gc.ykqx.R;
import com.gc.ykqx.service.entity.ResponseMessage;
import com.gc.ykqx.ui.custom.LazyFragment;
import com.gc.ykqx.ui.custom.MenuView;
import com.gc.ykqx.ui.custom.PinchImageView;
import com.gc.ykqx.service.util.Constant;
import com.gc.ykqx.service.util.ParseUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.victor.loading.rotate.RotateLoading;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class MonFragment extends LazyFragment implements MenuView.OnFinishChooseListener, CompoundButton.OnCheckedChangeListener {


    private static final String TAG = "MonFragment";
    @BindView(R.id.menu_view)
    MenuView menuView;
    @BindView(R.id.tv_title)
    TextView tvTime;
    @BindView(R.id.btn_previous)
    ImageButton btnPrevious;
    @BindView(R.id.btn_next)
    ImageButton btnNext;
    @BindView(R.id.ck_play)
    CheckBox ckPlay;
    @BindView(R.id.img)
    PinchImageView img;
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.rotateloading)
    RotateLoading rotateloading;
    Unbinder unbinder;
    private String fileDir;//图片目录  00 01 02 03 1 2
    private String picNameUrl;//图片名字url
    private List<String> picNameList;//图片url
    private String picName;//文件名字
    private List<String> picUrlList;//图片url
    private String picUrl;//图片名字url
    private String picPath;// 图片本地地址

    private boolean isPrepared;//是否准备好
    private boolean isLoaded;//是否加载过
    private ResponseMessage message;
    private Gson gson;
    private String menuId;
    private int index;
    private PlayRunnable runnable;//定时器
    private Handler handler = new Handler();
    private int downSum;
    private boolean isPlay;
    private String title;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public MonFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mon, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        isPrepared = true;
        // lazyLoad();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG, "onStart: " + "reload");
        loadData();
    }

    private void init() {
        gson = new Gson();
        picUrlList = new ArrayList<>();
        picNameList = new ArrayList<>();
        runnable = new PlayRunnable();
        menuId = "00";
        ckPlay.setOnCheckedChangeListener(MonFragment.this);
        menuView.setOnFinishChooseListener(MonFragment.this);
    }

    /*
    下载图片名字
     */
    public void downFileName() {
        rotateloading.start();
        OkHttpUtils
                .get()
                .url(picNameUrl)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        if (rotateloading != null) {
                            rotateloading.stop();
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "downFileName：" + response);
                        if (rotateloading != null) {
                            rotateloading.stop();
                        }
                        parseFileName(response);
                    }
                });
    }

    /*
    解析图片名字
     */
    private void parseFileName(String response) {//最新文件名字 世界时 MOSAICHREF000.20170517.075000.GIF
        if (picNameList != null) {
            picNameList.clear();
        }
        message = gson.fromJson(response, new TypeToken<ResponseMessage>() {
        }.getType());
        if (message != null) {
            if (message.getStatus() == Constant.Msg.RESPONSE_SUCCESS_CODE) {
                List<String> list = message.getFileNames();
                for (int i = list.size() - 1; i > -1; i--) {
                    picNameList.add(list.get(i));
                }
                if (picNameList != null && picNameList.size() >= 0) {
                    index = picNameList.size() - 1;
                    getPicName();
                }
            } else {
                Toast.makeText(getContext(), message.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

    }

    /*
    获取图片名字
     */
    private void getPicName() {
        picName = picNameList.get(index);//获取文件名字
        getFile();//获取文件
    }

    /*
    查看本地有无缓存
     */
    public void getFile() {
        fileDir = ParseUtil.getFileDir(menuId);
        picPath = fileDir + "/" + picName;
        File file = new File(picPath);
        if (file.exists()) {//本地存在
            if (isPlay) {
                downSum++;
                Log.e(TAG, "getFile: " + downSum);
                if (downSum == picNameList.size()) {
                    handler.postDelayed(runnable, 500);
                }
            } else {
                showImg();
            }
        } else {//不存在 网络加载
            picUrl = ParseUtil.getPicUrl(menuId, picName);
            downFile();
        }
    }


    /*
    下载图片
     */
    private void downFile() {
        rotateloading.start();
        OkHttpUtils
                .get()
                .url(picUrl)
                .build()
                .execute(new FileCallBack(fileDir, picName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        if (rotateloading != null) {
                            rotateloading.stop();
                        }
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Log.e(TAG, "downFile: " + response.getName());
                        if (rotateloading != null) {
                            rotateloading.stop();
                        }
                        if (isPlay) {
                            downSum++;
                            Log.e(TAG, "onResponse: " + downSum);
                            if (downSum == picNameList.size()) {
                                handler.postDelayed(runnable, 500);
                            }
                        } else {
                            showImg();
                        }
                    }
                });
    }

    /*
    显示图片
     */
    private void showImg() {
        if (rotateloading != null) {
            rotateloading.stop();
        }
        Bitmap bitmap = BitmapFactory.decodeFile(picPath);
        img.setImageBitmap(bitmap);
        // TODO: 2017/7/17
        showTime();
    }

    // TODO: 2017/7/17
    /*
    显示标题
     */
    private void showTime() {
        title = ParseUtil.getRadarTitle(menuId, picName);
        tvTime.setText(title);
    }

    @Override
    public void onFinishChosen(String id) {
        //      index = 0;
        ckPlay.setChecked(false);
        isPlay = false;
        this.menuId = id;
        switch (menuId) {
          /*  case "11":
            case "12":
            case "13":
            case "21":
            case "22":
            case "23":
                btnPrevious.setVisibility(View.VISIBLE);
                btnNext.setVisibility(View.VISIBLE);
                ckPlay.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
                getFileName();
                break;*/
            case "30":
                webView.reload();
                webView.setVisibility(View.VISIBLE);
                break;
            default:
              /*  btnPrevious.setVisibility(View.GONE);
                btnNext.setVisibility(View.GONE);
                ckPlay.setVisibility(View.GONE);*/
                webView.setVisibility(View.GONE);
                getFileName();
                break;
        }
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || isLoaded) {
            return;
        }
        loadData();
        isLoaded = true;
    }

    private void loadData() {
        getFileName();
        loadUrl(webView);
    }

    private void getFileName() {
        picNameUrl = ParseUtil.getPicNameUrl(menuId);
        downFileName();
    }

    @OnClick({R.id.btn_previous, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_previous:
                if (index > 0) {
                    index--;
                    getPicName();
                } else {
                    Toast.makeText(getContext(), Constant.NO_DATA_HINT, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_next:
                if (index < picNameList.size() - 1) {
                    index++;
                    getPicName();
                } else {
                    Toast.makeText(getContext(), Constant.NO_DATA_HINT, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        downSum = 0;
        isPlay = isChecked;
        if (isPlay) {
            btnPrevious.setClickable(false);
            btnNext.setClickable(false);
            for (int i = 0; i < picNameList.size(); i++) {
                picName = picNameList.get(i);
                getFile();
            }
        } else {
            btnPrevious.setClickable(true);
            btnNext.setClickable(true);
            handler.removeCallbacks(runnable);
        }
    }

    private void loadUrl(final WebView webView) {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {//不跳转系统浏览器,完成后提示消失
            @Override
            public void onPageFinished(WebView view, String url) {
            }
        });
        webView.loadUrl(Constant.Url.TYP_URL);
    }

    class PlayRunnable implements Runnable {

        @Override
        public void run() {
            index++;
            if (index == picNameList.size()) {
                index = 0;
            }
            picName = picNameList.get(index);
            picPath = fileDir + "/" + picName;//文件路径
            showImg();
            handler.postDelayed(runnable, 1000);
        }
    }

}